<template>
  <!-- #ifndef MP-TOUTIAO -->
  <custom-nav-bar title="搜索"></custom-nav-bar>
  <!-- #endif -->
  <view class="searchLayout">
    <!-- 搜索栏 -->
    <view class="search">
      <view class="categorySelector">
        <picker @change="bindCategoryChange" :value="categoryIndex" :range="categories">
          <view class="categoryPicker">
            {{ categories[categoryIndex] || '请选择类别' }}
            <uni-icons type="arrowdown" size="20"></uni-icons>
          </view>
        </picker>
      </view>
      <uni-search-bar
        @confirm="onSearch"
        @cancel="onClear"
        @clear="onClear"
        focus
        placeholder="搜索"
        v-model="queryParams.keyword"
      >
      </uni-search-bar>
    </view>

    <view v-if="!classList.length && !noSearch">
      <view class="history" v-if="historySearch.length">
        <view class="topTitle">
          <view class="text">最近搜索</view>
          <view class="icon" @click="removeHistory">
            <uni-icons type="trash" size="25"></uni-icons>
          </view>
        </view>
        <view class="tabs">
          <view class="tab" v-for="tab in historySearch" :key="tab" @click="clickTab(tab)">
            {{ tab }}
          </view>
        </view>
      </view>

      <view class="recommend">
        <view class="topTitle">
          <view class="text">热门搜索</view>
        </view>
        <view class="tabs">
          <view class="tab" v-for="tab in recommendList" :key="tab" @click="clickTab(tab)">
            {{ tab }}
          </view>
        </view>
      </view>
    </view>

    <view class="noSearch" v-if="noSearch">
      <view class="text">暂无搜索结果</view>
    </view>

    <!-- 搜索结果列表 -->
    <view v-else>
      <view class="list">
        <navigator
          v-if="categoryIndex === 1"
          :url="`/pages/preview/preview?id=${item.id}`"
          class="item"
          v-for="item in classList"
        >
          <image :src="item.smallPicurl" mode="aspectFill"></image>
          <view class="description">{{ item.description }}</view>
        </navigator>
        <navigator
          v-else
          :url="`/pages/preview/previewAlbum?id=${item.id}`"
          class="item"
          v-for="item in classList">
          <image :src="item.imgUrl" mode="aspectFill"></image>
          <view class="description">{{ item.description }}</view>
        </navigator>

      </view>
      <view class="loadingLayout" v-if="noData || classList.length">
        <uni-load-more :status="noData ? 'noMore' : 'loading'" />
      </view>
    </view>
  </view>
</template>
<script setup>
import { ref } from 'vue'
import { onUnload, onReachBottom } from '@dcloudio/uni-app'
import { apiGetWallList, apiGetAlbumList } from '@/api/apis.js'
import CustomNavBar from '@/components/custom-nav-bar/custom-nav-bar.vue'

// 类别选项
const categories = ['专辑', '壁纸']
const categoryIndex = ref(0)

// 绑定类别变化事件
const bindCategoryChange = (e) => {
  const index = e.detail.value
  categoryIndex.value = index
}

// 根据所选类别调用不同的API
const apiCaller = async (params) => {
  switch (categoryIndex.value) {
    case 0:
      return await apiGetAlbumList(params)
    case 1:
      return await apiGetWallList(params)
    default:
      return { data: [] }
  }
}

// 初始化查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 12,
  keyword: '',
})

// 搜索历史词
const historySearch = ref(uni.getStorageSync('historySearch') || [])

// 热门搜索词
const recommendList = ref(['动漫', '萌宠', '自然', '人物'])

// 没有更多
const noData = ref(false)
// 没有搜索结果
const noSearch = ref(false)

// 搜索结果列表
const classList = ref([])

// 处理搜索逻辑
const handleSearch = async () => {
  try {
    uni.showLoading({ title: '加载中...' })
    // 重置分页
    queryParams.value.pageNum = 1
    classList.value = []

    const res = await apiCaller(queryParams.value)
    console.log('搜索结果', res)
    if (res && res.rows) {
      classList.value = [...classList.value, ...res.rows]
      uni.setStorageSync('storgClassList', classList.value)
      noData.value = classList.value.length < queryParams.value.pageSize
      noSearch.value = classList.value.length === 0

      // 更新历史搜索记录
      if (queryParams.value.keyword.trim()) {
        const updatedHistory = [
          queryParams.value.keyword,
          ...historySearch.value.filter((item) => item !== queryParams.value.keyword),
        ].slice(0, 5) // 限制最多5个历史记录

        historySearch.value = updatedHistory
        uni.setStorageSync('historySearch', updatedHistory)
      }
    } else {
      console.warn('Unexpected response format from API')
      noSearch.value = true
    }
  } catch (error) {
    console.error(error)
    uni.showToast({ title: '搜索失败，请稍后再试', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 点击搜索
const onSearch = () => {
  handleSearch()
}

// 查询数据（用于分页加载）
const loadMore = async () => {
  queryParams.value.pageNum++
  try {
    const res = await apiCaller(queryParams.value)
    if (res && res.rows) {
      // 过滤并映射结果
      const filteredRows = res.rows
        .filter((item) => item.description && item.description.includes(queryParams.value.keyword))
        .map((item) => ({
          ...item,
          smallPicurl: item.imgUrl || item.smallPicurl || '', // 确保有 smallPicurl 字段
        }))

      classList.value = [...classList.value, ...filteredRows]
      uni.setStorageSync('storgClassList', classList.value)
      noData.value = filteredRows.length < queryParams.value.pageSize
    }
  } catch (error) {
    console.error(error)
  }
}

// 点击清除按钮
const onClear = () => {
  initParams()
}

// 点击标签进行搜索
const clickTab = (value) => {
  initParams(value)
  onSearch()
}

// 点击清空搜索记录
const removeHistory = () => {
  uni.showModal({
    title: '是否清空历史搜索？',
    success: (res) => {
      if (res.confirm) {
        uni.removeStorageSync('historySearch')
        historySearch.value = []
      }
    },
  })
}

// 初始化参数
const initParams = (value = '') => {
  classList.value = []
  noData.value = false
  noSearch.value = false
  queryParams.value = {
    pageNum: 1,
    pageSize: 12,
    keyword: value || '',
  }
}

// 触底加载更多
onReachBottom(() => {
  if (!noData.value) {
    loadMore()
  }
})

// 关闭页面
onUnload(() => {
  // 如果需要清除缓存中的 classList，则应如下操作：
  uni.removeStorageSync('storgClassList')
})
</script>
<style lang="scss" scoped>
.searchLayout {
  padding: 20rpx;
  display: flex;
  flex-direction: column;

  .search {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 40rpx;
    overflow: hidden;
    margin-bottom: 20rpx;

    .categorySelector {
      padding: 0 20rpx;
      height: 60rpx;
      line-height: 60rpx;
      background-color: #f7f7f7;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      position: relative;
      z-index: 1;

      .categoryPicker {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 32rpx;
        color: #999;
        transition: background-color 0.3s ease;
      }

      .categoryPicker:hover {
        background-color: #eee;
      }
    }

    ::v-deep .uni-searchbar {
      flex-grow: 1;
      border-radius: 0 40rpx 40rpx 0;
      background-color: #fff;
      padding-left: 10rpx;

      &__box {
        flex-grow: 1;
        border-radius: 0 40rpx 40rpx 0;
        background-color: #fff;
        padding-left: 0;
      }

      &__input-box {
        background-color: transparent !important;
        padding-left: 0;
      }

      &__placeholder-class {
        color: #999;
      }

      &__cancel-btn {
        color: #999;
      }
    }
  }

  .topTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 36rpx;
    color: #333;
    margin-bottom: 10rpx;
  }

  .history,
  .recommend {
    padding: 20rpx;
    background-color: #fff;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
    margin-bottom: 20rpx;
  }

  .tabs {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding-top: 10rpx;

    .tab {
      background: #f4f4f4;
      font-size: 28rpx;
      color: #333;
      padding: 10rpx 28rpx;
      border-radius: 50rpx;
      margin-right: 20rpx;
      margin-top: 20rpx;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #ddd;
      }
    }
  }

  .list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200rpx, 1fr));
    gap: 20rpx;
    padding: 20rpx 10rpx;

    .item {
      height: 440rpx;
      overflow: hidden;
      border-radius: 20rpx;
      box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
      }

      image:hover {
        transform: scale(1.05);
      }
    }
  }

  .loadingLayout {
    text-align: center;
    margin-top: 20rpx;
  }
}
</style>
